package com.futvan.z.framework.core;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Properties;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.web.method.HandlerMethod;

import com.alibaba.fastjson.JSONObject;
import com.futvan.z.framework.util.SystemUtil;
import com.futvan.z.system.zlog.z_log;
import com.futvan.z.system.zorg.z_org;
import com.futvan.z.system.zuser.z_user;
/**
 * SQL拦截器
 * @author zj
 *
 */
@Intercepts(
		value = { 
				@Signature (type=Executor.class,method="update",args={MappedStatement.class,Object.class}),
				@Signature(type=Executor.class,method="query",args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class,CacheKey.class,BoundSql.class}),
				@Signature(type=Executor.class,method="query",args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})
		}
		)

public class SqlInterceptor extends SuperZ implements Interceptor {


	/**
	 * 实现拦截的地方
	 * */
	public Object intercept(Invocation invocation) throws Throwable {
		Object target = invocation.getTarget();
		Object result = null;
		if (target instanceof Executor) {

			//获取执行sqlid方法
			String sqlid = "";
			if (invocation.getArgs().length > 1 && invocation.getArgs()[0]!=null) {  
				org.apache.ibatis.mapping.MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
				sqlid = ms.getId();
			}

			//设置开始时间
			long beginTime = System.currentTimeMillis();

			//获取SQL
			String sqlinfo = "";  
			if (invocation.getArgs().length > 1 && invocation.getArgs()[1]!=null) {  
				sqlinfo = String.valueOf(invocation.getArgs()[1]);
			}

			//执行方法
			result = invocation.proceed();

			//设置结束时间
			long endTime = System.currentTimeMillis();
			BigDecimal times = (new BigDecimal(endTime).subtract(new BigDecimal(beginTime))).divide(new BigDecimal(1000),4, BigDecimal.ROUND_DOWN);
			String sid = "";
			if(z.sp!=null) {
				sid = z.sp.get("sid");
			}

			if("true".equals(z.sp.get("isPrintSQL"))) {
				z.Log("[耗时:"+times+"秒][SQLID:"+sqlid+"][SQL:"+sqlinfo+"]");
			}

		}
		return result;
	}

	/**
	 * Plugin.wrap生成拦截代理对象
	 * */
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	public void setProperties(Properties properties) {

	}


}
